import React, { useCallback, useEffect, useRef, useState } from 'react'
import { NavBar, Toast } from 'antd-mobile'
import { useNavigate, useSearchParams } from 'react-router-dom'
import style from './video.module.css'
import request from '../../../api/request'
import defaultAvatar from '../../../assets/homeimg/logo.png'

function Index() {
	const nav = useNavigate()
	const [search] = useSearchParams()
	const categoryIdFromQuery = Number(search.get('categoryId') || 0)
	const [categories, setCategories] = useState([]) // [{id,name}]
	const [activeCategoryId, setActiveCategoryId] = useState(0)
	const [videos, setVideos] = useState([])
	const [page, setPage] = useState(1)
	const [currentIndex, setCurrentIndex] = useState(0)
	const [loadingVideos, setLoadingVideos] = useState({})
	const [isLoadingMore, setIsLoadingMore] = useState(false)
	const [isDragging, setIsDragging] = useState(false)
	const [dragOffset, setDragOffset] = useState(0)
	const [progressMap, setProgressMap] = useState({}) // idx -> 0..1
	const [seekingIndex, setSeekingIndex] = useState(null)
	const [seekingPercent, setSeekingPercent] = useState(0)
	// 评论相关
	const [showComments, setShowComments] = useState(false)
	const [commentsLoading, setCommentsLoading] = useState(false)
	const [comments, setComments] = useState([])
	const [commentInput, setCommentInput] = useState('')
	const [isSending, setIsSending] = useState(false)
	const [commentVideoId, setCommentVideoId] = useState(null)
	const miniAppliedRef = useRef(false)

	const count = 5
	const touchStartYRef = useRef(0)
	const touchEndYRef = useRef(0)
	const containerRef = useRef(null)
	const videoRefs = useRef([])
	const headerRef = useRef(null)
	const commentsPanelRef = useRef(null)

	// 获取类目并初始化选中项
	const fetchCategories = useCallback(async () => {
		try {
			const res = await request.get('/user/video/v1/findVideoCategoryList')
			const list = res?.data?.result || []
			setCategories(list)
			const initial = categoryIdFromQuery || list?.[0]?.id || 0
			setActiveCategoryId(initial)
		} catch (err) {
			console.error(err)
			Toast.show('获取类目失败')
		}
	}, [categoryIdFromQuery])

	const fetchVideos = useCallback(async (nextPage) => {
		if (isLoadingMore || !activeCategoryId) return
		setIsLoadingMore(true)
		try {
			const res = await request.get('/user/video/v1/findVideoVoList', {
				params: { categoryId: activeCategoryId, page: nextPage, count }
			})
			const list = res?.data?.result || []
			console.log(`加载类目${activeCategoryId} 第${nextPage}页视频:`, list)
			if (list.length === 0) {
				if (nextPage > 1) {
					Toast.show('已回到开始')
					setPage(1)
					setCurrentIndex(0)
					setVideos([])
				} else {
					Toast.show('暂无视频')
				}
				setIsLoadingMore(false)
				return
			}
			setVideos((prev) => [...prev, ...list])
			setPage(nextPage)
		} catch (error) {
			console.error(error)
			Toast.show('视频加载失败')
		} finally {
			setIsLoadingMore(false)
		}
	}, [activeCategoryId, count])

	useEffect(() => {
		fetchCategories()
		const originalOverflow = document.body.style.overflow
		document.body.style.overflow = 'hidden'
		return () => {
			document.body.style.overflow = originalOverflow
		}
	}, [fetchCategories])

	// 类目变更时，重置并拉取第一页
	useEffect(() => {
		if (!activeCategoryId) return
		setVideos([])
		setCurrentIndex(0)
		setPage(1)
		fetchVideos(1)
	}, [activeCategoryId])

	// 切换当前视频时，自动播放当前并暂停其他
	useEffect(() => {
		videoRefs.current.forEach((el, idx) => {
			if (!el) return
			if (idx === currentIndex) {
				el.play().catch(() => {})
			} else {
				el.pause()
				el.currentTime = 0
			}
		})
	}, [currentIndex, videos.length])

	const handleTouchStart = (e) => {
		touchStartYRef.current = e.touches[0].clientY
		touchEndYRef.current = touchStartYRef.current
		setIsDragging(true)
		setDragOffset(0)
	}

	const handleTouchMove = (e) => {
		if (!isDragging) return
		touchEndYRef.current = e.touches[0].clientY
		const deltaY = touchEndYRef.current - touchStartYRef.current
		const maxDrag = window.innerHeight * 0.9
		const clampedDelta = Math.max(-maxDrag, Math.min(maxDrag, deltaY))
		setDragOffset(clampedDelta)
	}

	const goNext = () => {
		if (currentIndex < videos.length - 1) {
			setCurrentIndex((idx) => idx + 1)
			if (currentIndex + 2 >= videos.length) {
				fetchVideos(page + 1)
			}
		} else {
			fetchVideos(page + 1)
		}
	}

	const goPrev = () => {
		if (currentIndex > 0) setCurrentIndex((idx) => idx - 1)
	}

	const handleTouchEnd = () => {
		setIsDragging(false)
		setDragOffset(0)
		const deltaY = touchEndYRef.current - touchStartYRef.current
		const threshold = 80
		if (Math.abs(deltaY) < threshold) return
		if (deltaY < 0) goNext()
		else goPrev()
	}

	const togglePlay = (idx, e) => {
		if (e) e.stopPropagation()
		const el = videoRefs.current[idx]
		if (!el) return
		if (el.paused) el.play()
		else el.pause()
	}

	// 平滑缩放：保持宽高比，用统一 scale，水平方向居中，顶部贴 header，底部不超过评论面板
	const animateToMini = () => {
		const el = videoRefs.current[currentIndex]
		if (!el || miniAppliedRef.current) return
		const first = el.getBoundingClientRect()
		const headerBottom = headerRef.current ? headerRef.current.getBoundingClientRect().bottom : 64
		const panelTop = commentsPanelRef.current ? commentsPanelRef.current.getBoundingClientRect().top : Math.round(window.innerHeight * 0.45)
		const availWidth = window.innerWidth
		const availHeight = Math.max(80, panelTop - headerBottom)
		const s = Math.min(availWidth / first.width, availHeight / first.height) // 等比缩放
		const targetWidth = first.width * s
		const targetLeft = (window.innerWidth - targetWidth) / 2
		const targetTop = headerBottom
		const dx = targetLeft - first.left
		const dy = targetTop - first.top
		el.style.willChange = 'transform'
		el.style.transformOrigin = 'top left'
		el.style.zIndex = '199'
		el.animate([
			{ transform: 'translate(0px, 0px) scale(1)' },
			{ transform: `translate(${dx}px, ${dy}px) scale(${s})` }
		], { duration: 260, easing: 'cubic-bezier(.2,.6,.2,1)', fill: 'forwards' })
		miniAppliedRef.current = true
	}
	const animateToFull = () => {
		const el = videoRefs.current[currentIndex]
		if (!el || !miniAppliedRef.current) return
		el.style.transformOrigin = 'top left'
		el.animate([
			{ transform: getComputedStyle(el).transform },
			{ transform: 'translate(0px, 0px) scale(1)' }
		], { duration: 240, easing: 'cubic-bezier(.2,.6,.2,1)', fill: 'forwards' }).finished.then(() => {
			el.style.willChange = ''
			el.style.zIndex = ''
			el.style.transformOrigin = ''
		})
		miniAppliedRef.current = false
	}

	// 视频进度处理
	const handleTimeUpdate = (idx, e) => {
		const el = e.target
		if (!el.duration) return
		const percent = el.currentTime / el.duration
		setProgressMap((prev) => ({ ...prev, [idx]: percent }))
	}

	const handleLoadedMetadata = (idx, e) => {
		const el = e.target
		if (!el.duration) return
		setProgressMap((prev) => ({ ...prev, [idx]: 0 }))
	}

	// 评论：打开并加载
	const openComments = async (videoId) => {
		setShowComments(true)
		setCommentsLoading(true)
		setCommentVideoId(videoId)
		try {
			const res = await request.get('/user/video/v1/findVideoCommentList', { params: { videoId } })
			const list = res?.data?.result || []
			setComments(list)
		} catch (err) {
			console.error(err)
			Toast.show('加载评论失败')
		} finally {
			setCommentsLoading(false)
			requestAnimationFrame(animateToMini)
		}
	}

	const closeComments = () => {
		setShowComments(false)
		requestAnimationFrame(animateToFull)
	}

	const handleSeekStart = (idx, e) => {
		e.stopPropagation()
		const touch = e.touches ? e.touches[0] : e
		const rect = e.currentTarget.getBoundingClientRect()
		const percent = Math.max(0, Math.min(1, (touch.clientX - rect.left) / rect.width))
		setSeekingIndex(idx)
		setSeekingPercent(percent)
	}

	const handleSeekMove = (idx, e) => {
		if (seekingIndex !== idx) return
		e.stopPropagation()
		const touch = e.touches ? e.touches[0] : e
		const rect = e.currentTarget.getBoundingClientRect()
		const percent = Math.max(0, Math.min(1, (touch.clientX - rect.left) / rect.width))
		setSeekingPercent(percent)
	}

	const handleSeekEnd = (idx, e) => {
		if (seekingIndex !== idx) return
		e.stopPropagation()
		const el = videoRefs.current[idx]
		if (el && el.duration) {
			el.currentTime = seekingPercent * el.duration
		}
		setProgressMap((prev) => ({ ...prev, [idx]: seekingPercent }))
		setSeekingIndex(null)
	}

	const sendComment = async () => {
		const content = commentInput.trim()
		if (!content) {
			Toast.show('请输入评论内容')
			return
		}
		if (!commentVideoId) return
		if (isSending) return
		setIsSending(true)
		try {
			const res = await request.post('/user/verify/v1/addVideoComment', { videoId: commentVideoId, content })
			// 简单判断成功，直接本地插入
			setComments((prev) => [{ id: Date.now(), content }, ...prev])
			setCommentInput('')
			Toast.show('已发送')
		} catch (err) {
			console.error(err)
			Toast.show('发送失败')
		} finally {
			setIsSending(false)
		}
	}

	const onInputKeyDown = (e) => {
		if (e.key === 'Enter') {
			e.preventDefault()
			sendComment()
		}
	}

	return (
		<div className={style.container}>
			{/* 头部导航 */}
			<div className={style.header} ref={headerRef}>
				<NavBar className={style.navbar} onBack={() => nav(-1)}>
					<div className={style.tabBar}>
						{categories.map((c) => (
							<span
								key={c.id}
								className={`${style.tabItem} ${activeCategoryId === c.id ? style.activeTab : ''}`}
								onClick={() => setActiveCategoryId(c.id)}
							>
								{c.name}
							</span>
						))}
					</div>
				</NavBar>
			</div>

			{/* 视频列表 */}
			<div
				ref={containerRef}
				onTouchStart={handleTouchStart}
				onTouchMove={handleTouchMove}
				onTouchEnd={handleTouchEnd}
				className={style.videoContainer}
				style={{ 
					transform: `translateY(calc(-${currentIndex * 100}% + ${dragOffset}px))`,
					transition: isDragging ? 'none' : 'transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)'
				}}
			>
				{videos.map((item, idx) => (
					<div key={`video-${activeCategoryId}-${idx}-${item.id || Date.now()}`} className={style.videoItem}>
						<video
							ref={(el) => (videoRefs.current[idx] = el)}
							src={item.originalUrl || item.shearUrl}
							className={style.video}
							playsInline
							preload="metadata"
							controls={false}
							onClick={() => togglePlay(idx)}
							onLoadStart={() => setLoadingVideos(prev => ({ ...prev, [idx]: true }))}
							onCanPlay={() => setLoadingVideos(prev => ({ ...prev, [idx]: false }))}
							onTimeUpdate={(e) => handleTimeUpdate(idx, e)}
							onLoadedMetadata={(e) => handleLoadedMetadata(idx, e)}
							onError={(e) => {
								console.error('视频加载失败:', item.originalUrl || item.shearUrl, e)
								setLoadingVideos(prev => ({ ...prev, [idx]: false }))
							}}
						/>

						{/* 加载占位符 */}
						{loadingVideos[idx] && (
							<div className={style.loadingPlaceholder}>
								<div className={style.loadingSpinner}></div>
								<span>视频加载中...</span>
							</div>
						)}

						{/* 右侧操作按钮（评论打开时隐藏） */}
						{!showComments && (
							<div className={style.rightActions}>
								<div className={style.actionItem} onClick={(e) => { e.stopPropagation(); Toast.show('点赞功能开发中') }}>
									<div className={style.actionIcon}>❤️</div>
									<div className={style.actionText}>点赞</div>
								</div>
								<div className={style.actionItem} onClick={(e) => { e.stopPropagation(); openComments(item.id) }}>
									<div className={style.actionIcon}>💬</div>
									<div className={style.actionText}>评论</div>
								</div>
								<div className={style.actionItem} onClick={(e) => { e.stopPropagation(); Toast.show('收藏功能开发中') }}>
									<div className={style.actionIcon}>⭐</div>
									<div className={style.actionText}>收藏</div>
								</div>
								<div className={style.actionItem} onClick={(e) => { e.stopPropagation(); Toast.show('分享功能开发中') }}>
									<div className={style.actionIcon}>📤</div>
									<div className={style.actionText}>分享</div>
								</div>
							</div>
						)}

						{/* 底部信息 */}
						<div className={style.bottomInfo}>
							<div className={style.authorInfo}>
								<div className={style.authorAvatar}>
									<img src={item.headPic || defaultAvatar} alt="头像" />
								</div>
								<div className={style.authorName}>{item.nickName || '健康科普'}</div>
								<div className={style.followBtn}>+ 关注</div>
							</div>
							<div className={style.videoCaption}>{item.title || '健康科普视频'}</div>
							<div className={style.musicInfo}>🎵 健康科普音乐</div>
						</div>
					</div>
				))}
			</div>

			{/* 全局进度条 */}
			<div
				className={style.globalProgressBar}
				onTouchStart={(e) => handleSeekStart(currentIndex, e)}
				onTouchMove={(e) => handleSeekMove(currentIndex, e)}
				onTouchEnd={(e) => handleSeekEnd(currentIndex, e)}
				onMouseDown={(e) => handleSeekStart(currentIndex, e)}
				onMouseMove={(e) => seekingIndex === currentIndex ? handleSeekMove(currentIndex, e) : undefined}
				onMouseUp={(e) => handleSeekEnd(currentIndex, e)}
			>
				<div className={style.progressTrack}>
					<div className={style.progressFill} style={{ width: `${Math.round(100 * (seekingIndex === currentIndex ? seekingPercent : (progressMap[currentIndex] || 0)))}%` }} />
					<div className={style.progressThumb} style={{ left: `${Math.round(100 * (seekingIndex === currentIndex ? seekingPercent : (progressMap[currentIndex] || 0)))}%` }} />
				</div>
			</div>

			{/* 评论抽屉 */}
			{showComments && (
				<div className={style.commentsMask} onClick={closeComments}>
					<div className={style.commentsPanel} ref={commentsPanelRef} onClick={(e) => e.stopPropagation()}>
						<div className={style.commentsHeader}>
							<span>评论</span>
							<span className={style.commentsClose} onClick={closeComments}>×</span>
						</div>
						<div className={style.commentsBody}>
							{commentsLoading ? (
								<div className={style.commentsLoading}>加载中…</div>
							) : comments.length === 0 ? (
								<div className={style.commentsEmpty}>还没有评论</div>
							) : (
								<div className={style.commentsList}>
									{comments.map((c) => (
										<div key={c.id} className={style.commentItem}>
											<div className={style.commentAvatar}><img src={defaultAvatar} alt="头像" /></div>
											<div className={style.commentContent}>{c.content}</div>
										</div>
									))}
								</div>
							)}
						</div>
						<div className={style.commentsFooter}>
							<input
								className={style.commentsInput}
								placeholder="发一条友善的评论"
								value={commentInput}
								onChange={(e) => setCommentInput(e.target.value)}
								onKeyDown={onInputKeyDown}
							/>
							<button className={style.sendBtn} disabled={isSending} onClick={sendComment}>
								发送
							</button>
						</div>
					</div>
				</div>
			)}
		</div>
	)
}

export default Index
